package servlets;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;

import org.json.JSONArray;
import org.json.JSONObject;

import structures.Product;
import structures.ProductList;

public class SearchKeywordsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String SECURITY_APPNAME = "Politecn-2c1c-4683-a770-019912d3cb8b";
	private static final String OP_NAME = "findItemsByKeywords";
	private static final String SERVICE_VERS = "1.0.0";
	private static final String GLOBAL_ID = "EBAY-US";
	private static final String ENCODING = "JSON";
	private static final int MAX_RESULTS = 3;
	private static final String SERVICE_URI = "http://svcs.ebay.com/services/search/FindingService/v1";
	
	private JSONObject json;
	private String apiCall;
	private String keywords;
	
	private JSONObject item = new JSONObject();
	private String result = "";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		JsonManager manager = new JsonManager();
		ProductList productList = new ProductList();
		
		keywords = request.getParameter("keywords").replace(" ", "%20");
		
		apiCall = SERVICE_URI + "?OPERATION-NAME=" + OP_NAME +
				"&SERVICE-VERSION=" + SERVICE_VERS +
				"&SECURITY-APPNAME=" + SECURITY_APPNAME + 
				"&GLOBAL-ID=" + GLOBAL_ID +
				"&RESPONSE-DATA-FORMAT=" + ENCODING +
				"&REST-PAYLOAD" +
				"&keywords=" + keywords +
				"&paginationInput.entriesPerPage=" + MAX_RESULTS;
		
		URL url;
		URLConnection connection;
		try {
			url = new URL(apiCall);
			connection = url.openConnection();
			
			String line, resp;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			
			while ((line = reader.readLine()) != null) {
	            builder.append(line);
	        }

	        resp = builder.toString();
	        
	        json = new JSONObject(resp);
	        
	        JSONArray itemsArray = json.getJSONArray("findItemsByKeywordsResponse");
	        
	        JSONObject root = itemsArray.getJSONObject(0);
	        JSONArray searchResult = root.getJSONArray("searchResult");
	        
	        JSONObject root2 = searchResult.getJSONObject(0);
	        JSONArray items = root2.getJSONArray("item");
	       
	        for(int i = 0; i < MAX_RESULTS; i++) {
	        	JSONObject obj = items.getJSONObject(i);
	        	item.put("type", "ebay");
	        	item.put("image", obj.get("galleryURL"));
	        	item.put("title", obj.get("title"));
	        	item.put("link", obj.get("viewItemURL"));
	        	item.put("id", obj.get("itemId"));
	        	
	        	String product = item.toString();
	        	product = product.replace("[", "");
	        	product = product.replace("]", "");
	        	Product p = new Product();
	        	p = manager.toProduct(product);
	        	
	        	productList.getList().add(p);
	        	
	        	/*
	        	result += item.toString();
	        	if (i < (MAX_RESULTS - 1)) {
		        	result += ",";
				}*/
	        }
	        
	        String listP = manager.generateJSON(productList);
	        
	        /*
	        result = result.replace("[", "");
	        result = result.replace("]", "");
	        */
	        response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			
			response.getWriter().write(listP);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

}
